package com.example.asa;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/deleteDisaster")
public class DeleteDisasterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        HttpSession session = request.getSession();

        // 获取灾情ID
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("message", "请选择要删除的灾情");
            RequestDispatcher dispatcher = request.getRequestDispatcher("disasterManage.jsp");
            dispatcher.forward(request, response);
            return;
        }

        int disasterId = Integer.parseInt(idStr);

        // 数据库操作 - 删除灾情信息
        Connection conn = null;
        PreparedStatement stmt = null;
        boolean commitSuccess = false;

        try {
            conn = DatabaseUtil.getConnection();
            // 开启手动提交事务
            conn.setAutoCommit(false);

            String sql = "DELETE FROM disasters WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, disasterId);

            int rowsDeleted = stmt.executeUpdate();

            // 提交事务
            conn.commit();
            commitSuccess = true;

            if (rowsDeleted > 0) {
                // 使用session存储消息，因为重定向会丢失request中的属性
                session.setAttribute("message", "灾情信息删除成功!");
            } else {
                session.setAttribute("message", "灾情信息删除失败，请重试");
            }

        } catch (SQLException e) {
            System.err.println("Error deleting disaster: " + e.getMessage());
            e.printStackTrace();

            // 回滚事务
            if (conn != null && !commitSuccess) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

            // 设置错误消息
            session.setAttribute("errorMessage", "删除灾情信息时发生数据库错误: " + e.getMessage());

        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 重定向回灾情列表页面
        response.sendRedirect(request.getContextPath() + "/emergencyPage.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}